package base.多线程.同步代码;

import java.util.Random;

public class MM_Thread extends Thread{
    /*所有对象共享数据*/
    static int ticket = 0;
    /*锁对象，一定唯一*/
    static final Object lock = new Object();

    @Override
    public void run() {
        while (true) {
            Random r = new Random();
            int time = r.nextInt(1000);
            try {
                Thread.sleep(time);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            synchronized(MM_Thread.class){
                if (ticket < 100){


                    ticket++;
                    System.out.println(getName()+"正在卖出第"+ticket+"张票！");
                    Thread.yield();

                }else {
                    System.out.println("抱歉，票已经售罄~");
                    break;
                }
            }
        }
    }
}
